package com.campus.common.service.impl;

import com.campus.common.domain.LoginUser;
import com.campus.common.domain.User;
import com.campus.common.domain.UserInfo;
import com.campus.common.dto.UserDto;
import com.campus.common.enums.OnlineStatusEnum;
import com.campus.common.enums.VerifyCodeEnum;
import com.campus.common.exception.SystemException;
import com.campus.common.exception.SystemExceptionCode;
import com.campus.common.exception.VerifyCodeException;
import com.campus.common.exception.VerifyCodeExceptionCode;
import com.campus.common.mapper.UserInfoMapper;
import com.campus.common.mapper.UserMapper;
import com.campus.common.service.UserService;
import com.campus.common.utils.RedisCache;
import jakarta.annotation.Resource;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private RedisCache redisCache;
    @Resource
    PasswordEncoder passwordEncoder;
    /**
     *
     * @param userDto
     * @return
     */

    @Override
    public void registerByEmail(UserDto userDto) {
        // 首先判断验证码是否正确，若存在则退出
        Integer verifyCode = redisCache.getCacheObject(VerifyCodeEnum.REGISTER_EMAIl_CODE.getCode() + userDto.getEmail());
        if(!Objects.equals(verifyCode, userDto.getVerifyCode())) {
            throw new VerifyCodeException(VerifyCodeExceptionCode.VERIFY_CODE_ERROR);
        }
        // 判断
        User user = userMapper.selectByEmail(userDto.getEmail());
        if (user != null) {
            throw new SystemException(SystemExceptionCode.USER_LOGIN_EMAIL_EXIST);
        }
        user = userMapper.selectByUsername(userDto.getUsername());
        if (user != null) {
            throw new SystemException(SystemExceptionCode.USER_LOGIN_USERNAME_EXIST);
        }
        // TODO 验证码发送以及用户注册我
        user = User.builder()
                .email(userDto.getEmail())
                .username(userDto.getUsername())
                .password(passwordEncoder.encode(userDto.getPassword()))
                .build();
        userMapper.insert(user);
        UserInfo userInfo = UserInfo.builder()
                .onlineStatus(OnlineStatusEnum.OLINE.getCode())
                .userId(user.getUserId())
                .build();
        // 创建用户信息
        userInfoMapper.insert(userInfo);
    }
    /**
     *
     * @param userDto
     * @return
     */
    @Override
    public void registerByPhoneNumber(UserDto userDto) {
    }

}
